/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ebedynky.services;

import ebedynky.beans.HibernateUtil;
import ebedynky.beans.User;
import ebedynky.editors.EditorFactory;
import java.util.List;
import org.hibernate.Session;

/**
 *
 * @author Azimus
 */
public class UserService {

    /**
     * Seesion - current connection to the db.
     */
    private Session session;

    /**
     * Constructor, retrieves the session (connection).
     */
    public UserService() {
        this.session = HibernateUtil.getSessionFactory().openSession();
    }

    /**
     * Closes the session (connection).
     * @return success/failure.
     */
    public boolean close() {
        this.session.close();
        return !(this.session.isOpen());
    }

    /**
     * Restarts the session (connection).
     * @return success/failure.
     */
    public boolean restart() {
        this.session.close();
        if (this.session.isOpen()) {
            throw new IllegalStateException("Session could not be closed.");
        }
        this.session = HibernateUtil.getSessionFactory().openSession();
        return this.session.isOpen();
    }

    /**
     * Retrieves a User identified by the ID.
     * @param id of the User
     * @return User with the ID given (null if not found)
     */
    public User getUserByID(int id) {
        session.beginTransaction();
        User us = (User) session.get(User.class, new Integer(id));
        session.getTransaction().commit();
        return (us);
    }

    /**
     * Retrieves a list of all Users stored in the db.
     * @return List of all Users (null if no Users)
     */
    public List<User> getAllUsers() {
        session.beginTransaction();
        List<User> suList = session.createQuery("from User").list();
        session.getTransaction().commit();
        return (suList);
    }

    /**
     * Searches the db for users with given parameters.
     * @param name user's name
     * @param surname user's surname
     * @param username user's username
     * @param email user's email
     * @param userID user's ID
     * @return list of corresponding users.
     */
    public List<User> FindUserByParameters(String name, String surname, String username, String email, int userID) {
        session.beginTransaction();
        String query = "from User where";
        String pattern = "([a-zA-Z]*)";
        if (!name.equals("") && EditorFactory.matches(name, pattern)) {
                query = query + " name = " + "'" + name + "'" + " AND";
        }
        if (!surname.equals("") && EditorFactory.matches(surname, pattern)) {
            query = query + " surname = " + "'" + surname + "'" + " AND";
        }
        if (!username.equals("") && EditorFactory.matches(surname, pattern)) {
            query = query + " surname = " + "'" + surname + "'" + " AND";
        }
        pattern = "^(([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+([;,](([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+)*$";
        if (!email.equals("") && EditorFactory.matches(email, pattern)) {
            query = query + " email = " + "'" + email + "'" + " AND";
        }
        if (userID > 0) {
            query = query + " userID = " + String.valueOf(userID) + " AND";
        }

        if (query.endsWith("AND")) {
            query = query.substring(0, query.length() - 3);
        }
        if (query.equals("from User where")) {
            query = "from User";
        }
        List<User> suList = session.createQuery(query).list();
        session.getTransaction().commit();
        return (suList);
    }

    /**
     * Retrieves a User identified by the username.
     * @param username of the User
     * @return User with the username given (null if not found)
     */
    public User getUserByUsername(String username) {
        String pattern = "([a-zA-Z0-9-_]*)";
        if (EditorFactory.matches(username, pattern)) {
            String hql = "from User where username = '" + username + "'";
            List list = session.createQuery(hql).list();
            if (!list.isEmpty() && list.get(0) != null) {
                User user = (User) list.get(0);
                return user;
            } else {
                return null;
            }
        } else {
            throw new IllegalArgumentException("Illegal username: " + username + ". Possible SQLinjection?");
        }
    }

    /**
     * Changes the account state of selected user (by id) to allowed (true).
     * @param id of the user to change account state
     */
    public void ChangeAccoutStateToAllow(int id) {
        session.beginTransaction();
        User su = (User) session.get(User.class, new Integer(id));
        su.setAccountState(true);
        session.flush();
        session.getTransaction().commit();
        session.clear();
    }

    /**
     * Changes the account state of selected user (by id) to denied (false).
     * @param id of the user to change account state
     */
    public void ChangeAccoutStateToDeny(int id) {
        session.beginTransaction();
        User su = (User) session.get(User.class, new Integer(id));
        su.setAccountState(false);
        session.flush();
        session.getTransaction().commit();
        session.clear();
    }
}
